package com.hitqz.robot.driver.netty.protocol.message;


import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 解析内容对应协议上内容
 */
@Data
@NoArgsConstructor
public class GfMessage {

    public final static byte[] head = new byte[]{
            (byte) 0xFF, (byte) 0xAA
    };

    private byte length;

    private byte[] data;

    private byte checkSum;

    // 构造请求报文
    public GfMessage(byte[] data) {
        this.data = data;
        this.length = (byte) (data.length & 0xFF);
        //计算除“头部”和“校验和”以外的各字节的和
        int sum = 0;
        for (byte b : data) {
            sum += b & 0xFF; // 确保只考虑 byte 的低 8 位
        }
        sum += this.length & 0xFF;
        this.checkSum = (byte) (sum & 0xFF);
    }

    // 构造应答报文
    public GfMessage(byte length, byte[] data, byte checkSum) {
        this.length = length;
        this.data = data;
        this.checkSum = checkSum;
    }

    public String getCmdHexStr() {
        StringBuilder sb = new StringBuilder();
        sb.append("0x").append(String.format("%02X", data[0] & 0xFF));
        if (data.length > 1) {
            sb.append(String.format("%02X", data[1] & 0xFF));
        }
        return sb.toString();
    }

    // 校验数据
    public boolean doCheck() {
        int countCheckSum = 0;
        for (byte b : this.data) {
            countCheckSum += b & 0xFF; // 确保只考虑 byte 的低 8 位
        }
        countCheckSum += this.length & 0xFF;
        return this.checkSum == (byte) (countCheckSum & 0xFF);
    }
}
